# -*- encoding: utf-8 -*-
from flask import Flask, request
from flask import g
from flask_login import current_user
# here put the import lib
from .configs import init_Session
from .models import db
from .configs.config import Config


def create_app():
    app = Flask(__name__)

    app.config.from_object(Config)

    from .models import init_db
    init_db(app)

    init_Session(app, db)

    # CSRFProtect(app)

    from app.auth import init_auth
    init_auth(app)

    from .utils.commons import ReConverter
    app.url_map.converters["re"] = ReConverter

    from .api import init_api
    init_api(app)

    from .views import init_views
    init_views(app)
    return app


app = create_app()


@app.before_request
def before_request():
    g.user = current_user


# 创建全站拦截器，每个请求之后根据请求方法统一设置返回头
@app.after_request
def process_response(response):
    allow_cors = ['OPTIONS', 'PUT', 'DELETE', 'GET', 'POST']
    if request.method in allow_cors:
        response.headers["Access-Control-Allow-Origin"] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'OPTIONS,GET,POST,PUT,DELETE'
        response.headers['Access-Control-Allow-Headers'] = 'content-type,x-ijt'
    return response


@app.route("/test")
def test():
    return "test success"